package db

import (
	"fmt"
	"log"
	"time"

	"os"
	"os/exec"

	"github.com/spf13/viper"
)

func BackUpJob() {
	go func() {
		//备份：每小时执行一次备份
		backUpTicker := time.NewTicker(20 * time.Second)
		defer backUpTicker.Stop()
		for {
			select {
			case <-backUpTicker.C:
				if err := BackUp(); err != nil {
					log.Printf("备份失败: %v", err)
				}
			}
		}
	}()
}

func BackUp() error {
	mongoBackUpBaseDir := viper.GetString("mongoBackUpBaseDir")
	yMdHms := time.Now().Format("20060102150405")
	backUpUri := mongoBackUpBaseDir + "/" + yMdHms
	err := os.MkdirAll(backUpUri, 0755)
	if err != nil {
		fmt.Printf("创建目录失败: %v\n", err)
	} else {
		fmt.Println("目录创建成功")
	}
	//dir, err := os.Getwd()
	//if err != nil {
	//	log.Fatal(err)
	//}
	//cmdKey := "cmd.exe /C e:\\bin\\mongodump.exe --gzip --out " + backUpUri

	args := []string{
		"--gzip",
		"--out",
		backUpUri,
	}

	cmd := exec.Command("cmd.exe", " -Command ", "E:/bin/mongodump.exe")
	cmd.Args = append(cmd.Args, args...)
	output, err := cmd.CombinedOutput()
	if err != nil {
		log.Fatalf("执行命令失败: %v\n输出: %s", err, string(output))
	}
	return nil
}

func Restore(backUpDir string) error {
	dir, err := os.Getwd()
	if err != nil {
		log.Fatal(err)
	}
	cmdKey := dir + "/mongo/bin/mongorestore.exe --host localhost --port 27017 --gzip --dir " + backUpDir
	cmd := exec.Command(cmdKey)
	output, err := cmd.CombinedOutput()
	if err != nil {
		log.Fatalf("执行命令失败: %v\n输出: %s", err, string(output))
	}
	return nil
}
